import type { FC } from 'react';
import React, { useState, useContext, useEffect } from 'react';
import { context, usePrefersColor } from 'dumi/theme';
import './Device.less';

interface IDeviceProps {
  className?: string;
  url: string;
}

const HashTAG = '#/mobile';
const DemoPublicPath = '/h5/';
function now() {
  const n = new Date();
  return `${n.getHours()}:${n.getMinutes()}`;
}

const Device: FC<IDeviceProps> = ({ url, className }) => {
  const [renderKey, setRenderKey] = useState(Math.random());
  const [curTime, setTime] = useState(now());
  const [demoUrl, updateUrl] = useState<string | null>(null);
  const [color] = usePrefersColor();
  const {
    config: { mode },
  } = useContext(context);

  // re-render iframe if prefers color changed
  useEffect(() => {
    setRenderKey(Math.random());
  }, [color]);

  useEffect(() => {
    if (location.hash.indexOf(HashTAG) === 0) {
      const hash = `#/pages${location.hash.replace(HashTAG, '')}/index`;
      updateUrl(
        `${location.origin}${location.pathname}${DemoPublicPath}${hash}`,
      );
    } else {
      updateUrl(url);
    }

    const timer = setInterval(() => {
      setTime(now());
    }, 1000 * 60);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div
      className={['__dumi-default-device'].concat(className).join(' ')}
      data-device-type="iOS"
      data-mode={mode}
    >
      <div className="__dumi-default-device-status">
        <span>PXXDesign</span>
        <span>{curTime}</span>
      </div>
      {demoUrl && (
        <iframe title="dumi-previewer" src={demoUrl} key={renderKey} />
      )}
      <div className="__dumi-default-device-action">
        <button
          className="__dumi-default-icon"
          role="refresh"
          onClick={() => setRenderKey(Math.random())}
        />
        {/* <button className="__dumi-default-icon" role="qrcode">
          <QRCode value={url} size={96} />
        </button> */}
        {demoUrl && (
          <a
            href={demoUrl}
            target="_blank"
            rel="noreferrer"
            className="__dumi-default-icon"
            role="open-demo"
          />
        )}
      </div>
    </div>
  );
};

export default Device;
